import md5 from "md5";
import Talk from '../controller/talk';
import Login from '../controller/login';
import MakeClientMsgPackage from '../controller/makeTemporaryTalk'
import Heartbeat from '../controller/heartbeat';
import TalkObject from "./talkObject";
const talkObject = new TalkObject();
import GetTalkDetail from '../controller/getTalkDetail';
const messageObject = {
    talk: new Talk(),
    login: new Login(),
    makeTemporaryTalk: new MakeClientMsgPackage(),
    heartbeat: new Heartbeat(),
    getTalkDetail: new GetTalkDetail(),
}
export class Sendcontroller {
    static instance = null;                                 // 发送器实例
    static messageArray = [];                               // 通讯列表
    constructor(options) {
        if (!Sendcontroller.instance) {
            Sendcontroller.instance = this;
        }
        Sendcontroller.instance.so = options;
        return Sendcontroller.instance;
    }
    /* 创建，添加到消息队列*/
    pushMessage(sign, data, toMemberId, succCallback, failCallback) {
        /*创建消息主体*/
        const makeClientMsgPackage = (typeTitle, data, fromMemberId = 0) => {
            var arr = [{
                type: "talk",                               //消息类型
                keys: ["talk_id", "type", "content"]        //必填字段
            },
            {
                type: "makeTemporaryTalk",
                keys: ["dialogueKey"]
            },
            {
                type: "login",                                                            //登录
                keys: ["key", "loginKey", "token", "sertype", "isForceLogin"],
            },
            {
                type: "heartbeat",
                keys: [],
            },
            {
                type: 'getTalkDetail',
                keys: [],
            }
            ]
            const dataKeys = Object.keys(data);
            // 必填字段
            const messageKeyList = arr.find(item => { if (item.type == typeTitle) { return item; } })
            if (!messageKeyList) { return { code: 301, data: "消息类型未定义！" } }
            const key = messageKeyList.keys.find(key => { if (!dataKeys.includes(key)) { return key } })
            if (key) { return { code: 301, data: "缺失字段" + key } }
            var myDate = new Date();
            var outData = {
                head: {
                    po: 2,
                    ms: 1,
                    fromMemberId,
                    clientMsgId: "",
                    action: messageKeyList.type,
                    dateTime: myDate.toLocaleTimeString(),
                },
                body: {},
            };
            dataKeys.forEach(key => { outData["body"][key] = data[key]; })           //消息body 字段填充
            const md5String = md5(JSON.stringify(outData) + Date.now());
            outData["head"]["clientMsgId"] = fromMemberId + "_" + md5String;
            return { data: outData, code: 200 };
        }
        if (sign != "login") {
            if (toMemberId == 0) { return { code: 301, data: "请登录！" } }
        }
        var content = makeClientMsgPackage(sign, data, toMemberId)              // 创建消息
        if (content.code != 200) {
            // console.log(content)
            return { code: 301, data: "程序错误" };
        }
        // console.log('消息创建时间:', test());
        content.data.client = {
            addTime: test(),
            sendTime: '',
            sendStatus: 1,  //1 正在发送 2.发送成功 3. 发送失败
            sendNum: 0,
            succCallback: succCallback ? succCallback : '',
            failCallback: failCallback ? failCallback : ''
        }
        const messageData = JSON.parse(JSON.stringify(content));                 //深拷贝
        messageObject[content.data.head.action].sendMessage(messageData.data);   //talk 添加聊天记录操作
        Sendcontroller.messageArray.unshift(content);                        //添加到通讯队列
        return { code: 200, data: content };
    }
    /* 发送消息*/
    sendMessage(clientMsgId) {
        // var clientMsgId = msg.data.head.clientMsgId;
        const message = Sendcontroller.messageArray.find(message => {
            if (message.data.head.clientMsgId === clientMsgId) { return message; }
        })
        // if (msg.code != 200) { return alert("消息发送失败！格式错误！") }
        if (message) {
            this.testSendMessage(message.data, 0);         //talk,login,MakeTemporaryTalk
        } else {
            this.so.send(JSON.stringify(message.data));    //Heartbeat
        }
    }
    /* 收到回执信息*/
    getServerReceiptMsg(data) {
        // console.log('收到回执时间:', test());
        if (data.body.code != 200) { return }
        var receiverServerTime = test();
        //1.在通讯队列中找到该消息对象
        const message = Sendcontroller.messageArray.find(message => {                // 改变消息的状态
            if (message.data.head.clientMsgId === data.head.clientMsgId) { return message; }
        });
        if (!message) { return }                                                     //在通讯队列中未找到该消息对象，不再后续操作                        
        //2.改变消息队列的状态 和 发送时间
        var client = message.data.client;
        client.sendTime = data.head.dateTime;                                        //消息发送时间
        client.updateTime = test();                                              //消息修改时间
        client.receiverServerTime = receiverServerTime;
        client.sendStatus = 3;
        console.log('消息改变状态时间:', test());
        // console.log("第四步", client);
        talkObject.changeMessageStatus(data.head.clientMsgId);
        //4.不同类型的消息操作（makeTemporaryTalk 会返回一条消息 talk类型消息重新发送）
        let message01 = messageObject[data.head.action].receiptMsg(data.body);       //MakeTemporaryTalk 类型返回一条talk类型消息
        if (message01.code != 200) { /*console.log("会话队列不存在此消息。");*/ return; }  //当消息不存在时
        message01 = message01.data;
        const relMessage = this.pushMessage(message01.sign, message01.data, talkObject.member_id);               //发送消息
        if (relMessage.code != 200) { /*console.log(data.data);*/ return }
        this.sendMessage(relMessage.data.data.head.clientMsgId);
        client.succCallback ? client.succCallback(data.body.data.talk.id) : '';      //创建临时会话成功的回调c中改变消息的状态
    }
    /* */
    testSendMessage(content, count) {
        let length = 4;
        if (count >= length) {
            if (content.client.sendStatus != 3) {
                content.client.sendStatus = 2;
                content.client.fail = true;
                content.client.failCallback && content.client.failCallback("请求超时！");
                console.log("消息发送失败！");
            }
            return
        }
        if (content.client.sendStatus != 3) {
            content.client.sendNum++;
            this.so.send(JSON.stringify(content));
            console.log(test(), count)
            setTimeout(() => { this.testSendMessage(content, count + 1); }, 1000);
        }
    }
    sendReceiverMsg(msg) {
        this.so.send(JSON.stringify(msg.data));
    }
}
function test() {
    var now = new Date();
    var str,
        second = now.getSeconds() < 10 ? 0 + '' + now.getSeconds() : now.getSeconds(),
        minSecond = (Date.now() + '').slice(-3);
    str = second + '.' + minSecond;
    return str;
}